<template>
  <div class="process-form-container">
    <el-card>
      <div slot="header">
        <span>{{ isEdit ? '编辑流程' : '创建流程' }}</span>
      </div>
      
      <el-form ref="processForm" :model="processForm" :rules="processRules" label-width="120px">
        <el-form-item label="流程名称" prop="processName">
          <el-input v-model="processForm.processName" placeholder="请输入流程名称" />
        </el-form-item>
        
        <el-form-item label="流程分类" prop="category">
          <el-select v-model="processForm.category" placeholder="请选择分类">
            <el-option label="请假申请" value="leave" />
            <el-option label="报销申请" value="reimbursement" />
            <el-option label="采购申请" value="purchase" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="流程描述" prop="description">
          <el-input
            v-model="processForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入流程描述"
          />
        </el-form-item>
        
        <el-form-item label="流程图标">
          <el-select v-model="processForm.icon" placeholder="请选择图标">
            <el-option
              v-for="icon in iconOptions"
              :key="icon.value"
              :label="icon.label"
              :value="icon.value"
            >
              <span style="display: flex; align-items: center;">
                <i :class="icon.value" style="margin-right: 8px; font-size: 18px;"></i>
                <span>{{ icon.label }}</span>
              </span>
            </el-option>
          </el-select>
          <span v-if="processForm.icon" style="margin-left: 10px;">
            <i :class="processForm.icon" style="font-size: 24px; color: #409EFF;"></i>
          </span>
        </el-form-item>
        
        <el-form-item label="表单配置" prop="formConfig">
          <el-button @click="showFormDesigner = true">设计表单</el-button>
          <span v-if="processForm.formConfig" style="margin-left: 10px; color: #67C23A;">
            已配置
          </span>
          <span v-else style="margin-left: 10px; color: #F56C6C;">
            未配置
          </span>
        </el-form-item>
        
        <el-form-item label="流程配置" prop="processConfig">
          <el-button @click="showProcessDesigner = true" icon="el-icon-s-operation" type="primary">
            流程设计
          </el-button>
          <span v-if="processForm.processConfig" style="margin-left: 10px; color: #67C23A;">
            <i class="el-icon-success"></i> 已配置
          </span>
          <span v-else style="margin-left: 10px; color: #F56C6C;">
            <i class="el-icon-error"></i> 未配置
          </span>
        </el-form-item>
        
        <el-form-item label="状态">
          <el-switch
            v-model="processForm.status"
            :active-value="1"
            :inactive-value="0"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSubmit">保存</el-button>
          <el-button @click="$router.back()">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 表单设计器对话框 -->
    <el-dialog 
      title="表单设计器" 
      :visible.sync="showFormDesigner" 
      width="90%" 
      top="5vh"
      :close-on-click-modal="false"
    >
      <form-designer v-model="processForm.formConfig" @save="handleFormSave" />
    </el-dialog>
    
    <!-- 流程设计器对话框 -->
    <el-dialog 
      title="流程设计" 
      :visible.sync="showProcessDesigner" 
      width="95%" 
      top="2vh"
      :close-on-click-modal="false"
      custom-class="professional-dialog"
    >
      <ProcessDesignProfessional v-model="processForm.processConfig" />
      <div slot="footer">
        <el-button @click="showProcessDesigner = false">取消</el-button>
        <el-button type="primary" @click="handleProcessSave">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getProcessById, createProcess, updateProcess, updateProcessWithVersion, checkRunningInstances } from '@/api/process'
import FormDesigner from '@/components/FormDesigner'
import ProcessDesignProfessional from './components/ProcessDesignProfessional'

export default {
  name: 'ProcessForm',
  
  components: {
    FormDesigner,
    ProcessDesignProfessional
  },
  
  data() {
    return {
      processForm: {
        processName: '',
        category: '',
        description: '',
        icon: 'el-icon-document',
        formConfig: '',
        processConfig: '',
        status: 1
      },
      processRules: {
        processName: [
          { required: true, message: '请输入流程名称', trigger: 'blur' }
        ],
        category: [
          { required: true, message: '请选择流程分类', trigger: 'change' }
        ],
        formConfig: [
          { required: true, message: '请配置表单', trigger: 'change' }
        ],
        processConfig: [
          { required: true, message: '请配置流程', trigger: 'change' }
        ]
      },
      showFormDesigner: false,
      showProcessDesigner: false,
      isEdit: false,
      // 图标选项列表
      iconOptions: [
        { label: '文档', value: 'el-icon-document' },
        { label: '编辑', value: 'el-icon-edit' },
        { label: '设置', value: 'el-icon-setting' },
        { label: '票据', value: 'el-icon-tickets' },
        { label: '表单', value: 'el-icon-s-order' },
        { label: '文件夹', value: 'el-icon-folder' },
        { label: '文件', value: 'el-icon-files' },
        { label: '日历', value: 'el-icon-date' },
        { label: '时钟', value: 'el-icon-time' },
        { label: '用户', value: 'el-icon-user' },
        { label: '团队', value: 'el-icon-s-custom' },
        { label: '位置', value: 'el-icon-location' },
        { label: '购物车', value: 'el-icon-shopping-cart-2' },
        { label: '办公', value: 'el-icon-office-building' },
        { label: '手机', value: 'el-icon-mobile-phone' },
        { label: '邮件', value: 'el-icon-message' },
        { label: '铃铛', value: 'el-icon-bell' },
        { label: '工具', value: 'el-icon-s-tools' },
        { label: '帮助', value: 'el-icon-s-help' },
        { label: '数据', value: 'el-icon-s-data' }
      ]
    }
  },
  
  created() {
    if (this.$route.params.id) {
      this.isEdit = true
      this.$store.commit('setIsEdit', true)
      this.loadProcess()
    } else {
      this.$store.commit('setIsEdit', false)
      // 如果是从分类视图创建，自动填充分类
      const category = this.$route.query.category
      if (category) {
        this.processForm.category = category
      }
    }
  },
  
  mounted() {
    if (this.isEdit) {
      this.loadProcess()
    }
  },
  
  methods: {
    loadProcess() {
      getProcessById(this.$route.params.id)
        .then(res => {
          console.log('加载流程数据:', res.data)
          this.processForm = res.data
          
          // 确保processConfig是字符串
          if (this.processForm.processConfig) {
            console.log('流程配置内容:', this.processForm.processConfig)
            try {
              // 将流程配置加载到Vuex store中
              const processData = JSON.parse(this.processForm.processConfig)
              this.$store.commit('loadForm', { 
                formItems: [], 
                process: processData 
              })
            } catch (e) {
              console.error('解析流程配置失败:', e)
            }
          } else {
            console.log('流程配置为空')
          }
        })
        .catch(error => {
          console.error('加载流程失败:', error)
        })
    },
    
    handleFormSave(formConfig) {
      this.processForm.formConfig = formConfig
      this.showFormDesigner = false
      this.$message.success('表单设计已保存')
      // 触发表单验证
      this.$refs.processForm.validateField('formConfig')
    },
    
    handleSubmit() {
      this.$refs.processForm.validate(valid => {
        if (valid) {
          // 保存前验证流程配置
          if (this.processForm.processConfig) {
            console.log('开始验证流程配置:', this.processForm.processConfig)
            const validation = this.validateProcessConfig(this.processForm.processConfig)
            console.log('验证结果:', validation)
            if (!validation.valid) {
              this.$message.warning(validation.message)
              return
            }
          }
          
          if (this.isEdit) {
            // 编辑时使用版本管理
            this.handleEditWithVersion()
          } else {
            // 创建时使用普通方法
            createProcess(this.processForm)
              .then(() => {
                this.$message.success('创建成功')
                this.$router.push('/processes')
              })
              .catch(error => {
                console.error('创建流程失败:', error)
              })
          }
        }
      })
    },
    
    // 处理编辑时的版本管理
    async handleEditWithVersion() {
      try {
        // 先检查是否有正在运行的实例
        const runningCheck = await checkRunningInstances(this.$route.params.id)
        const hasRunningInstances = runningCheck.data.hasRunningInstances
        const runningCount = runningCheck.data.runningInstanceCount
        
        if (hasRunningInstances) {
          // 有正在运行的实例，询问用户选择更新策略
          this.$confirm(
            `该流程有 ${runningCount} 个正在运行的实例。请选择更新策略：`,
            '版本管理',
            {
              confirmButtonText: '创建新版本',
              cancelButtonText: '强制更新',
              distinguishCancelAndClose: true,
              type: 'warning'
            }
          ).then(() => {
            // 用户选择创建新版本
            this.updateProcessWithStrategy('CREATE_NEW_VERSION')
          }).catch((action) => {
            if (action === 'cancel') {
              // 用户选择强制更新
              this.$confirm('强制更新可能影响正在运行的实例，确定继续吗？', '确认强制更新', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                this.updateProcessWithStrategy('FORCE_UPDATE')
              })
            }
          })
        } else {
          // 没有正在运行的实例，直接更新
          this.updateProcessWithStrategy('CREATE_NEW_VERSION')
        }
      } catch (error) {
        console.error('检查运行实例失败:', error)
        this.$message.error('检查流程状态失败')
      }
    },
    
    // 使用指定策略更新流程
    updateProcessWithStrategy(strategy) {
      const processData = {
        processName: this.processForm.processName,
        category: this.processForm.category,
        processXml: this.processForm.processXml,
        formConfig: this.processForm.formConfig,
        processConfig: this.processForm.processConfig,
        description: this.processForm.description,
        icon: this.processForm.icon,
        updateStrategy: strategy
      }
      
      updateProcessWithVersion(this.$route.params.id, processData)
        .then(() => {
          const message = strategy === 'CREATE_NEW_VERSION' ? '已创建新版本' : '流程已强制更新'
          this.$message.success(message)
          this.$router.push('/processes')
        })
        .catch(error => {
          console.error('更新流程失败:', error)
          this.$message.error('更新流程失败: ' + (error.response?.data?.message || error.message))
        })
    },
    
    // 验证流程配置
    validateProcessConfig(configStr) {
      try {
        const config = JSON.parse(configStr)
        
        // 检查是否有根节点
        if (!config || !config.id) {
          return { valid: false, message: '流程配置无效' }
        }
        
        // 使用与ProcessTree相同的验证逻辑
        const isValid = this.validateProcessTree(config)
        if (!isValid) {
          return { valid: false, message: '请根据提示完成流程节点设置😅' }
        }
        
        return { valid: true, message: '流程配置验证通过' }
      } catch (e) {
        return { valid: false, message: '流程配置格式错误' }
      }
    },
    
    // 使用与ProcessTree相同的验证逻辑
    validateProcessTree(node) {
      // 模拟ProcessTree的验证逻辑
      let valid = true
      
      const validateNode = (node) => {
        // 这里我们无法直接调用组件的validate方法，因为ProcessForm中没有组件实例
        // 所以我们使用简化的验证逻辑
        
        // 检查节点是否为空对象（没有type属性）
        if (!node.type) {
          return // 空对象不需要验证
        }
        
        if (!node.name || node.name.trim() === '') {
          valid = false
          return
        }
        
        // 发起人节点不需要验证
        if (node.type === 'ROOT') {
          return
        }
        
        // 审批人节点需要根据assignedType进行验证
        if (node.type === 'APPROVAL') {
          const assignedType = node.props?.assignedType
          switch (assignedType) {
            case 'ASSIGN_USER':
              if (!node.props?.assignedUser || node.props.assignedUser.length === 0) {
                valid = false
              }
              break
            case 'ROLE':
              if (!node.props?.role || node.props.role.length === 0) {
                valid = false
              }
              break
            case 'FORM_USER':
              if (!node.props?.formUser || node.props.formUser === '') {
                valid = false
              }
              break
            // 其他类型不需要验证
          }
        }
        
        // 抄送节点需要验证
        if (node.type === 'CC') {
          if (!node.props?.assignedUser || node.props.assignedUser.length === 0) {
            valid = false
          }
        }
      }
      
      const validate = (node) => {
        if (!node) return
        
        // 检查节点是否为空对象（没有type属性）
        if (!node.type) {
          return // 空对象不需要验证
        }
        
        validateNode(node)
        
        // 递归验证子节点
        if (node.children && typeof node.children === 'object') {
          validate(node.children)
        }
        
        // 验证分支节点
        if (node.branchs && Array.isArray(node.branchs)) {
          node.branchs.forEach(branchNode => {
            validateNode(branchNode)
            validate(branchNode.children)
          })
        }
      }
      
      validate(node)
      return valid
    },
    
    // 递归验证节点（保留原有逻辑作为备用）
    validateNode(node, nodePath = '') {
      console.log('验证节点:', node.type, node.name, node)
      const nodeName = node.name || '未命名节点'
      const currentPath = nodePath ? `${nodePath} -> ${nodeName}` : nodeName
      
      // 检查节点名称
      if (!node.name || node.name.trim() === '') {
        console.error('节点名称验证失败:', node)
        return { valid: false, message: `节点缺少名称: ${currentPath}` }
      }
      
      // 发起人节点不需要验证（允许所有人发起）
      if (node.type === 'ROOT') {
        // 发起人节点总是通过验证
      }
      // 审批节点需要根据assignedType进行验证
      else if (node.type === 'APPROVAL') {
        const validationResult = this.validateApprovalNode(node)
        if (!validationResult.valid) {
          return validationResult
        }
      }
      // 抄送节点需要验证
      else if (node.type === 'CC') {
        if (!node.props || !node.props.assignedUser || node.props.assignedUser.length === 0) {
          return { valid: false, message: `${node.name}：请选择需要抄送的人员` }
        }
      }
      // 条件节点必须有条件分支
      else if (node.type === 'CONDITION') {
        if (!node.children || Object.keys(node.children).length === 0) {
          return { valid: false, message: `${node.name}：缺少条件分支配置` }
        }
      }
      // 空节点不需要额外验证
      else if (node.type === 'EMPTY') {
        // 空节点总是通过验证
      }
      
      // 递归检查子节点
      if (node.children && typeof node.children === 'object') {
        for (const [key, childNode] of Object.entries(node.children)) {
          const childValidation = this.validateNode(childNode, currentPath)
          if (!childValidation.valid) {
            return childValidation
          }
        }
      }
      
      return { valid: true, message: '节点验证通过' }
    },
    
    // 验证审批人节点
    validateApprovalNode(node) {
      const assignedType = node.props?.assignedType
      
      switch (assignedType) {
        case 'ASSIGN_USER':
          // 指定人员：必须设置审批人
          if (!node.props?.assignedUser || node.props.assignedUser.length === 0) {
            return { valid: false, message: `${node.name}：请设置审批人` }
          }
          break
        case 'ROLE':
          // 角色：必须设置角色
          if (!node.props?.role || node.props.role.length === 0) {
            return { valid: false, message: `${node.name}：请选择系统角色` }
          }
          break
        case 'FORM_USER':
          // 表单内联系人：必须选择表单项
          if (!node.props?.formUser || node.props.formUser === '') {
            return { valid: false, message: `${node.name}：请选择表单联系人项` }
          }
          break
        case 'SELF_SELECT':
        case 'LEADER_TOP':
        case 'LEADER':
        case 'SELF':
          // 这些类型不需要额外验证
          break
        default:
          return { valid: false, message: `${node.name}：请选择审批对象类型` }
      }
      
      return { valid: true, message: '审批人节点验证通过' }
    },
    
    // 流程设计器相关方法
    handleProcessSave() {
      // 从Vuex store中获取流程数据
      const processData = this.$store.state.design.process
      if (processData && processData.id) {
        // 将流程数据转换为JSON字符串保存
        this.processForm.processConfig = JSON.stringify(processData)
        this.$message.success('流程配置已保存')
        this.showProcessDesigner = false
        // 触发表单验证
        this.$refs.processForm.validateField('processConfig')
      } else {
        this.$message.warning('请先设计流程')
      }
    }
    
  }
}
</script>

<style scoped>
.process-form-container {
  max-width: 800px;
}


/* 专业设计器对话框样式 */
.professional-dialog .el-dialog {
  height: 90vh !important;
  margin-top: 2vh !important;
}

.professional-dialog .el-dialog__body {
  height: calc(90vh - 80px) !important;
  padding: 0 !important;
  overflow: hidden;
}

.professional-dialog .el-dialog__header {
  padding: 8px 20px !important;
  border-bottom: 1px solid #e0e0e0;
  height: 40px !important;
  line-height: 24px !important;
}

.professional-dialog .el-dialog__footer {
  padding: 8px 20px !important;
  border-top: 1px solid #e0e0e0;
  height: 40px !important;
}
</style>

